{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import struct\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import time, datetime\n",
    "import sys, getopt\n",
    "# import multiprocessing\n",
    "# import talib as tdx\n",
    "from easyquant import MongoIo\n",
    "import matplotlib.pyplot as plt\n",
    "# from easyquant.indicator.base import *\n",
    "# import QUANTAXIS as QA\n",
    "\n",
    "import talib\n",
    "import matplotlib.ticker as ticker\n",
    "from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\n",
    "from matplotlib.figure import Figure\n",
    "import mplfinance as mpf\n",
    "from matplotlib import gridspec\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def getStockByDate(stockData, date,code):\n",
    "    if date < stockData.index[0][0]:\n",
    "        return None\n",
    "    try:\n",
    "        return stockData.loc[date,code]\n",
    "    except:\n",
    "        return getStockByDate(stockData, date - datetime.timedelta(1), code)\n",
    "\n",
    "def getValidDate(year, month, day, nextday = True):\n",
    "    try:\n",
    "        return pd.Timestamp(year, month, day)\n",
    "    except:\n",
    "        # print('getValidDate', year, month, day)\n",
    "        if nextday:\n",
    "            return getValidDate(year, month + 1, 1)\n",
    "        else:\n",
    "            return getValidDate(year, month, day - 1)\n",
    "          \n",
    "def beforeDate(calcDate, year = 0, month = 0):\n",
    "    year = year + int(month / 12)\n",
    "    month = month - int(month / 12) * 12\n",
    "    if calcDate.month > month:\n",
    "        result = getValidDate(calcDate.year - year, calcDate.month - month, calcDate.day)\n",
    "    else:\n",
    "        result = getValidDate(calcDate.year - year - 1, calcDate.month + 12 - month, calcDate.day)\n",
    "    return result\n",
    "  \n",
    "def afterDate(calcDate, year = 0, month = 0):\n",
    "    year = year + int(month / 12)\n",
    "    month = month - int(month / 12) * 12\n",
    "    if calcDate.month + month > 12:\n",
    "        result = getValidDate(calcDate.year + year + 1, calcDate.month + month - 12, calcDate.day)\n",
    "    else:\n",
    "        result = getValidDate(calcDate.year + year, calcDate.month + month, calcDate.day)\n",
    "    return result\n",
    "\n",
    "def calcBAYMDateLst(calcDate, dstDate, year, month, before = True):\n",
    "    out = []\n",
    "    if before:\n",
    "        value = eval('beforeDate')(calcDate, year, month)\n",
    "        out.append(value)\n",
    "        while value > dstDate:\n",
    "            calcDate = value\n",
    "            value = eval('beforeDate')(calcDate, year, month)\n",
    "            out.append(value)\n",
    "    else:\n",
    "        value = eval('afterDate')(calcDate, year, month)\n",
    "        out.append(value)\n",
    "        while value < dstDate:\n",
    "            calcDate = value\n",
    "            value = eval('afterDate')(calcDate, year, month)\n",
    "            out.append(value)\n",
    "    return out\n",
    "\n",
    "def calcBAYMDate(calcDate, year, month, before = True):\n",
    "    if before:\n",
    "        value = eval('beforeDate')(calcDate, year, month)\n",
    "    else:\n",
    "        value = eval('afterDate')(calcDate, year, month)\n",
    "    return value\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def GannCheck(dataIn, code, lastDay, posB0Day, delta = 0.1, gannBase = {'y':30,'m':0}, gannList = [{'y':7,'m':6},{'y':2,'m':6},{'y':0,'m':7},{'y':0,'m':1}]):\n",
    "  #     data=dataIn.reset_index()\n",
    "#     data=data.set_index(['date'])\n",
    "#     lstDay = data.index[-1]\n",
    "    # code = data.index[-1][1] ##二维索引用\n",
    "    # lastDay = data.index[-1][0] ##数据最大日期\n",
    "    firstDay = data.index[0][0]\n",
    "    x0data = getStockByDate(data, posB0Day, code) #基础点1的数据\n",
    "    xedata = getStockByDate(data, lastDay, code) #基础点1的数据 \n",
    "    x1wight = 1 ##权重\n",
    "    pxedata = 0\n",
    "    pdelta = 0\n",
    "    tj0=gannList[0] ##基础计算目标\n",
    "    ##基础点2\n",
    "    posB1Day = calcBAYMDate(posB0Day, gannBase['y'], gannBase['m'], False)\n",
    "    if firstDay > posB0Day:\n",
    "        print('checkLoop1', firstDay, posB0Day, posB1Day)\n",
    "        return GannCheck(dataIn, code, lastDay, posB1Day, delta, gannBase, gannList)\n",
    "    pos0Day = None\n",
    "    pos1Day = None\n",
    "    if posB1Day > lastDay:\n",
    "        print('checkLoop2', firstDay, posB0Day, posB1Day)\n",
    "        result = GannSubCheck(data, code, lastDay, posB1Day, gannList, delta)\n",
    "        if result != None:\n",
    "            result['posB0'] = posB0Day\n",
    "            result['posB1'] = posB1Day\n",
    "        return result\n",
    "    else:\n",
    "        print('checkLoop2', posB1Day)\n",
    "        result = GannSubCheck(data, code, lastDay, posB0Day, [gannBase])\n",
    "        if result != None:\n",
    "            result['posB0'] = posB0Day\n",
    "            result['posB1'] = posB1Day\n",
    "        return result\n",
    "\n",
    "        # pos0Day = posB0Day\n",
    "        # pos1Day = posB1Day\n",
    "        # x0data = getStockByDate(data, pos0Day, code)\n",
    "        # x1data=getStockByDate(data, pos1Day, code)\n",
    "        # x1wight = x1data.close / x0data.close\n",
    "        # pxedata = getStockByDate(data, calcBAYMDate(lastDay, gannBase['y'], gannBase['m'], True), code) * x1wight\n",
    "        # pdelta = abs((pxedata.close - xedata.close ) / xedata.close )\n",
    "        # return {'posB0':posB0Day, 'posB1':posB1Day, 'pos0':pos0Day, 'pos1':pos1Day, 'w':x1wight, 'pdata':pxedata, 'pd':pdelta}\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def GannSubCheck(data, code, lastDay, posB1Day, gannList, delta = 0.1):\n",
    "    # code = data.index[-1][1] ##二维索引用\n",
    "    # lastDay = data.index[-1][0] ##数据最大日期\n",
    "    xedata = getStockByDate(data, lastDay, code) #基础点1的数据\n",
    "    firstDay = data.index[0][0]\n",
    "    tj1=gannList[0]\n",
    "    # print(tj1)\n",
    "    print('GannSubCheck0', lastDay, posB1Day, gannList)\n",
    "    pos0Day = None\n",
    "    pos1Day = None\n",
    "    x1wight = 1 ##权重\n",
    "    pxedata = 0\n",
    "    pdelta = 0\n",
    "    base2 = calcBAYMDate(posB1Day, tj1['y'], tj1['m'], True)\n",
    "    base1 = calcBAYMDate(base2, tj1['y'], tj1['m'], True)\n",
    "    if base2 < lastDay and base1 < lastDay and base1 > data.index[0][0]:\n",
    "        pos0Day = base1\n",
    "        pos1Day = base2\n",
    "        x0data = getStockByDate(data, pos0Day, code)\n",
    "        x1data = getStockByDate(data, pos1Day, code)\n",
    "        # print(pos0Day, pos1Day, x0data, x1data)\n",
    "        x1wight = x1data.close / x0data.close\n",
    "        pxedata = getStockByDate(data, calcBAYMDate(lastDay, tj1['y'], tj1['m'], True), code) * x1wight\n",
    "        pdelta = abs((pxedata.close - xedata.close ) / xedata.close )\n",
    "        if pdelta > delta:\n",
    "            if len(gannList) <= 1:\n",
    "                print('GannSubCheck None')\n",
    "                return None\n",
    "            else:\n",
    "                print('GannSubCheck1', gannList, pos0Day, pos1Day, pdelta)\n",
    "                return GannSubCheck(data, code, lastDay, posB1Day, gannList[1:], delta)\n",
    "        else:\n",
    "            print('GannSubCheck2', gannList, posB1Day, pdelta)\n",
    "            rule = \"%s:%s:Y%02d:M%02d\" % (str(pos0Day)[:10], str(pos1Day)[:10], tj1['y'], tj1['m'])\n",
    "            return {'pos0':pos0Day, 'pos1':pos1Day, 'w':x1wight, 'tj1':tj1, 'rule':rule}\n",
    "    else:\n",
    "        if base2 < firstDay:\n",
    "            return None\n",
    "        print('GannSubCheck3', base2)\n",
    "        return GannSubCheck(data, code, lastDay, base2, gannList, delta)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def forcast(code, lastDay, beforeStep, afterStep, delta = 0.1, predate = '1993-01-01', plot = None):\n",
    "    if predate < str(data.index[0][0])[:10]:\n",
    "        return None\n",
    "    print('forcast', predate, str(data.index[0][0])[:10])\n",
    "    col_name = predate.replace('-','')\n",
    "    year = int(predate[:4])\n",
    "    month = int(predate[6:7])\n",
    "    day = int(predate[9:10])\n",
    "    # outs=GannCheck(data, pd.Timestamp(1992,5,26), gannBase = {'y':30,'m':0}, gannList = [{'y':7,'m':6},{'y':2,'m':6},{'y':0,'m':7},{'y':0,'m':1}])\n",
    "    gannList = [{'y':15,'m':0},{'y':7,'m':6},{'y':2,'m':6},{'y':0,'m':7},{'y':0,'m':1}]\n",
    "    # gannList = [{'y':15,'m':0},{'y':7,'m':6},{'y':2,'m':6},{'y':0,'m':7},{'y':0,'m':3},{'y':0,'m':1}]\n",
    "    # gannList = [{'y':15,'m':0},{'y':7,'m':6},{'y':2,'m':6},{'y':1,'m':3},{'y':0,'m':7},{'y':0,'m':3},{'y':0,'m':1}]\n",
    "    # gannList = [{'y':28,'m':0},{'y':15,'m':0},{'y':7,'m':6},{'y':2,'m':6},{'y':0,'m':7},{'y':0,'m':1}]\n",
    "    outs=GannCheck(data, code, lastDay, pd.Timestamp(year,month,day), delta = delta, gannBase = {'y':30,'m':0}, gannList = gannList)\n",
    "    if outs == None:\n",
    "        return None\n",
    "    # outs\n",
    "    # print('计算规则', outs['rule'])\n",
    "    data[col_name] = 0.0\n",
    "    x1wight=outs['w']\n",
    "    # print(x1wight)\n",
    "    gannBase=outs['tj1']\n",
    "    # print(gannBase)\n",
    "    # lastDay = data.index[-1][0]\n",
    "    # lastDay\n",
    "    # print(lastDay)\n",
    "    # code='000001'\n",
    "    firstDay = None\n",
    "    for rday in range(-beforeStep, afterStep):\n",
    "        ycday = lastDay + datetime.timedelta(rday)\n",
    "        if firstDay == None:\n",
    "            firstDay = ycday\n",
    "        # print(ycday)\n",
    "        preN = getStockByDate(data, calcBAYMDate(ycday, gannBase['y'], gannBase['m'], True), code) * x1wight\n",
    "        preD = afterDate(preN.name[0], year=0, month = 7)\n",
    "        try:\n",
    "            rclose = data.at[(ycday,code),'close']\n",
    "            # print(ycday)\n",
    "            rclose = getStockByDate(data, ycday, code).close\n",
    "            diff = preN.close - rclose\n",
    "        except Exception as e:\n",
    "    #         print(preN.name[0])\n",
    "            rclose = 0.0\n",
    "            diff = 0\n",
    "    #     print(str(preD)[:10], int(preN.close), rclose, int(diff))\n",
    "        if rclose == 0 and ycday < lastDay:\n",
    "    #         print(ycday)\n",
    "            continue\n",
    "        else:\n",
    "            if ycday.weekday() > 4:\n",
    "                continue\n",
    "            rclose = getStockByDate(data, ycday, code).close\n",
    "    #     print(ycday.weekday())\n",
    "        data.at[(ycday,code),col_name]  = preN.close\n",
    "        data.at[(ycday,code),'close']  = rclose\n",
    "        # data.at[]\n",
    "    # data.tail(30)\n",
    "    xlabel = []\n",
    "    for x in data.loc[(firstDay,code):].index:\n",
    "        xlabel.append(str(x[0])[5:10])\n",
    "    # data.iloc[-24:].close.plot()\n",
    "    # data.iloc[-24:][col_name].plot()\n",
    "    # plt.show()\n",
    "    if plot == None:\n",
    "        return None\n",
    "\n",
    "    plot.plot(xlabel, data.loc[(firstDay,code):][col_name], label=\"%s=>%s\" % (predate, outs['rule']))\n",
    "    return (firstDay, xlabel)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "code='000001'\n",
    "idx='1'\n",
    "beforeStep = 20\n",
    "afterStep = 20\n",
    "predict=['1992-05-26', '1997-05-12', '1996-12-11', '1996-01-19']\n",
    "# predict=['1997-05-12', '1996-12-11', '1996-01-19']\n",
    "# print(predict)\n",
    "\n",
    "# argv = sys.argv[1:]\n",
    "# code=argv[0]\n",
    "# idx=argv[1]\n",
    "# beforeStep = int(argv[2])\n",
    "# afterStep = int(argv[3])\n",
    "delta = 0.1\n",
    "# predict=argv[5:]\n",
    "print(delta, predict)\n",
    "\n",
    "code='600581'\n",
    "idx='0'\n",
    "\n",
    "m=MongoIo()\n",
    "if idx == '1':\n",
    "    data=m.get_index_day(code, st_start = '1990-01-01')\n",
    "else:\n",
    "    data=m.get_stock_day(code, st_start = '1990-01-01')\n",
    "lastDay = data.index[-1][0]\n",
    "print(code, lastDay)\n",
    "# print(data.head())\n",
    "# data=m.get_index_day(code, st_start = '1990-01-01')\n",
    "fig = plt.figure(figsize=(960/72,360/72))\n",
    "# fig, ax = plt.subplots()\n",
    "stockPlot = fig.add_subplot(1,1,1)\n",
    "text = stockPlot.text(0.5, 0.5, 'event', ha='center', va='center', fontdict={'size': 20})\n",
    "\n",
    "# text0 = plt.text(len_y-1,y[-1],str(y[-1]),fontsize = 10)\n",
    "firstDay = None\n",
    "xlabel = None\n",
    "for predata in predict:\n",
    "    print('step', predata)\n",
    "    temp = forcast(code, lastDay, beforeStep, afterStep, predate = predata, plot = stockPlot, delta = delta)\n",
    "    if firstDay == None and temp != None:\n",
    "        (firstDay, xlabel) = temp\n",
    "# forcast(code, col_name = '19970512', predate = '1997-05-12')\n",
    "\n",
    "if firstDay != None:\n",
    "    stockPlot.plot(xlabel, data.loc[(firstDay,code):]['close'], label=\"%s:REAL\" % code, linewidth = '2', color = '#00FF00')\n",
    "\n",
    "for label in stockPlot.xaxis.get_ticklabels():\n",
    "    label.set_rotation(45)\n",
    "# print(data.tail(30))\n",
    "# fig.canvas.mpl_connect('scroll_event', scroll)\n",
    "# fig.canvas.mpl_connect('motion_notify_event', motion)\n",
    "# fig.canvas.mpl_connect('button_press_event', call_back)\n",
    "\n",
    "plt.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data.filter(level)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data2=data.reset_index()\n",
    "data2['year'] = data2.date.dt.year\n",
    "data2.iloc[data2[data2['year'] == 2002]['close'].argmax()]\n",
    "\n",
    "# data2[data2['close']==data2['close'].groupby(data2.date.dt.year).max()]\n",
    "# data2['close'].groupby(data2.date.dt.year)\n",
    "\n",
    "# data2.close[data2['close'] == data2['close'].groupby(data2.date.dt.year).max()]\n",
    "# data2.tail()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data2.iloc[data2[data2['year'] == 2003]['close'].argmax()]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data2.iloc[63]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data['close'].groupby(level = 'date').idxmax()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df2.iloc[data2.close.max()]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 231,
   "metadata": {},
   "outputs": [],
   "source": [
    "def h_l_line(p_df, t=21,period=10000,fn=None):\n",
    "    \"\"\"\n",
    "    根据给定的周期找出最高最低点的日期和数据，然后计算对应的斐波纳契数据\n",
    "    :param fn: 高低线输出到文件,如果文件参数为None则不输出到文件\n",
    "    :param p_df:股票交易数据\n",
    "    :param t:数据周期\n",
    "    :param period:数据长度\n",
    "    :return:有效数据点，包括股票代码，日期，高低点周期交易天数、高低点周期自然天数\n",
    "    \"\"\"\n",
    "    if p_df is None or len(p_df)<t:\n",
    "        return None\n",
    "    # 获取最新的period条数据\n",
    "    # df1 = p_df.tail(period).reset_index(drop=True)\n",
    "    df1 = p_df[['close','high','low','trade_date','ts_code']].copy()\n",
    "    df1['cv'] = 0 #添加一列为后续保留值准备\n",
    "    high = df1['high']\n",
    "    low = df1['low']\n",
    "\n",
    "    # 保留数据的df\n",
    "    data = pd.DataFrame([])\n",
    "    #获取首行为有效的数据点,加入到保留数据框中\n",
    "    df1.loc[0,'cv'] = df1.iloc[0].high #最高价作为当前价\n",
    "    first = df1.iloc[0:1]\n",
    "    data = data.append(first)\n",
    "\n",
    "    #取第一个日期的最高值作为当前值,开始为0，默认为上涨周期\n",
    "    ci=0\n",
    "    cv=df1.iloc[ci].high\n",
    "    cup=True\n",
    "\n",
    "    #循环处理每一个周期\n",
    "    n=0\n",
    "    lt = t\n",
    "    while ci<df1.index.max():\n",
    "        n=n+1\n",
    "        # 取含当前日期的一个周期的最高和最低价以及索引值,如果出现下一个周期中当前点成为了这个周期的最高和最低点即当前点未变化则\n",
    "        # 在前周期长度上扩展1个周期,一旦出现拐点则恢复周期。\n",
    "        # 周期超高了数据长度则结束，当前点加入到数据有效点中。\n",
    "        # 为什么不是从下一个点找周期，因为下一个点开始的周期则一定存在一个高低点，而这个高低点和当前点的高点或低点比较后一定会\n",
    "        # 出现一个拐点，有时候不一定有拐点存在,所以要包含当前点\n",
    "        ih = high[ci:ci+lt].idxmax()\n",
    "        il = low[ci:ci+lt].idxmin()\n",
    "        ihv = df1.iloc[ih].high\n",
    "        ilv = df1.iloc[il].low\n",
    "        if (ih==ci) & (il==ci):\n",
    "            #数据结束了吗?如果结束了则直接添加当前数据到数据点和最后一个数据到数据点\n",
    "            if (ci+lt)>df1.index.max():\n",
    "                # 数据结束了,最后一个数据是否要添加到数据点中，由循环结束时处理\n",
    "                break\n",
    "            else:\n",
    "                # 三点重叠但数据为结束 , 周期延长重新计算\n",
    "                lt = lt + t\n",
    "                continue\n",
    "        if cup:\n",
    "            # 上涨阶段\n",
    "            if (ihv >= cv) & (ci != ih):\n",
    "                # 如果上升周期中最高价有更新则仍然上涨持续，上涨价格有效，下跌的价格为噪声\n",
    "                ci = ih\n",
    "                cv = ihv\n",
    "                cup = True\n",
    "            else:\n",
    "                # 未持续上涨，则下跌价格有效，出现了转折，此时上一个价格成为转折点价格,恢复计算周期\n",
    "                df1.loc[ci,'cv'] = cv\n",
    "                data = data.append(df1.iloc[ci:ci + 1])\n",
    "                ci = il\n",
    "                cv = ilv\n",
    "                cup = False\n",
    "                lt = t\n",
    "        else:\n",
    "            # 下跌阶段\n",
    "            if (ilv<=cv) & (ci != il):\n",
    "                # 下跌阶段持续创新低，则下跌价格有效，上涨价格为噪声\n",
    "                ci = il\n",
    "                cv = ilv\n",
    "                cup = False\n",
    "            else:\n",
    "                # 未持续下跌，此时转为上涨，上涨价格有效，此时上一个价格成为转折点价格,恢复计算周期\n",
    "                df1.loc[ci, 'cv'] = cv\n",
    "                data = data.append(df1.iloc[ci:ci + 1])\n",
    "                ci = ih\n",
    "                cv = ihv\n",
    "                cup = True\n",
    "                lt = t\n",
    "\n",
    "        # print(df1.iloc[ci:ci+1])\n",
    "        # print(n,ci,cv,cup,ih,il)\n",
    "\n",
    "        # if last+t>=df1.index.max():\n",
    "        #     # 最后计算恰好为最后一个周期，则直接加入最后一个周期进入数据有效点，并且结束循环\n",
    "        #     last = df1.index.max()\n",
    "        #     df1.loc[last, 'cv'] = df1.iloc[last].close\n",
    "        #     data = data.append(df1.iloc[last:last + 1])\n",
    "        #     break\n",
    "    #结束了，把当前点加入到数据有效点中\n",
    "    df1.loc[ci, 'cv'] = cv\n",
    "    data = data.append(df1.iloc[ci:ci + 1])\n",
    "    if ci != df1.index.max():\n",
    "        # 当前点不是最后一个点，则把最后一个点加入到数据点中\n",
    "        df1.loc[df1.index.max(), 'cv'] = df1.iloc[df1.index.max()].close\n",
    "        data = data.append(df1.tail(1))\n",
    "\n",
    "    data = data.reset_index(drop=False)\n",
    "    # 计算高低点转换的交易日数量即时间周期\n",
    "    data['period'] = (data['index'] - data['index'].shift(1)).fillna(0)\n",
    "    # 计算日期的差值,将字符串更改为日期\n",
    "    trade_date = pd.to_datetime(data['trade_date'],format='%Y-%m-%d')\n",
    "    days = trade_date - trade_date.shift(1)\n",
    "    # 填充后转换为实际的天数数字\n",
    "    days = (days.fillna(pd.Timedelta(0))).apply(lambda x:x.days)\n",
    "    data['days'] = days\n",
    "    # 对日期进行转换\n",
    "    data['trade_date']=trade_date.apply(lambda x:x.strftime('%Y-%m-%d'))\n",
    "    return data\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 233,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'1998-11-19'"
      ]
     },
     "execution_count": 233,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data=m.get_stock_day('000859', st_start = '1990-01-01')\n",
    "data3=data.copy()\n",
    "data3['trade_date'] = data3.index.levels[0]\n",
    "data3['ts_code'] = data3.index.levels[1][0]\n",
    "data3=data3.reset_index()\n",
    "hldata=h_l_line(data3, t = 240)\n",
    "predict = []\n",
    "for x in hldata.index:\n",
    "    predict.append(hldata.iloc[x].trade_date)\n",
    "predict[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 235,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>index</th>\n",
       "      <th>close</th>\n",
       "      <th>high</th>\n",
       "      <th>low</th>\n",
       "      <th>trade_date</th>\n",
       "      <th>ts_code</th>\n",
       "      <th>cv</th>\n",
       "      <th>period</th>\n",
       "      <th>days</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0</td>\n",
       "      <td>12.08</td>\n",
       "      <td>12.50</td>\n",
       "      <td>11.03</td>\n",
       "      <td>1998-11-19</td>\n",
       "      <td>000859</td>\n",
       "      <td>12.50</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>318</td>\n",
       "      <td>15.64</td>\n",
       "      <td>15.99</td>\n",
       "      <td>14.50</td>\n",
       "      <td>2000-03-29</td>\n",
       "      <td>000859</td>\n",
       "      <td>15.99</td>\n",
       "      <td>318.0</td>\n",
       "      <td>496</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>346</td>\n",
       "      <td>10.23</td>\n",
       "      <td>10.61</td>\n",
       "      <td>10.15</td>\n",
       "      <td>2000-05-15</td>\n",
       "      <td>000859</td>\n",
       "      <td>10.15</td>\n",
       "      <td>28.0</td>\n",
       "      <td>47</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>605</td>\n",
       "      <td>13.34</td>\n",
       "      <td>13.52</td>\n",
       "      <td>13.28</td>\n",
       "      <td>2001-06-13</td>\n",
       "      <td>000859</td>\n",
       "      <td>13.52</td>\n",
       "      <td>259.0</td>\n",
       "      <td>394</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>755</td>\n",
       "      <td>7.66</td>\n",
       "      <td>7.66</td>\n",
       "      <td>6.54</td>\n",
       "      <td>2002-01-23</td>\n",
       "      <td>000859</td>\n",
       "      <td>6.54</td>\n",
       "      <td>150.0</td>\n",
       "      <td>224</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>1042</td>\n",
       "      <td>9.67</td>\n",
       "      <td>10.38</td>\n",
       "      <td>9.45</td>\n",
       "      <td>2003-04-16</td>\n",
       "      <td>000859</td>\n",
       "      <td>10.38</td>\n",
       "      <td>287.0</td>\n",
       "      <td>448</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>1702</td>\n",
       "      <td>1.81</td>\n",
       "      <td>1.83</td>\n",
       "      <td>1.78</td>\n",
       "      <td>2006-03-08</td>\n",
       "      <td>000859</td>\n",
       "      <td>1.78</td>\n",
       "      <td>660.0</td>\n",
       "      <td>1057</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>1992</td>\n",
       "      <td>11.74</td>\n",
       "      <td>12.00</td>\n",
       "      <td>10.90</td>\n",
       "      <td>2007-05-28</td>\n",
       "      <td>000859</td>\n",
       "      <td>12.00</td>\n",
       "      <td>290.0</td>\n",
       "      <td>446</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>2342</td>\n",
       "      <td>2.20</td>\n",
       "      <td>2.30</td>\n",
       "      <td>2.15</td>\n",
       "      <td>2008-11-04</td>\n",
       "      <td>000859</td>\n",
       "      <td>2.15</td>\n",
       "      <td>350.0</td>\n",
       "      <td>526</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>2597</td>\n",
       "      <td>9.50</td>\n",
       "      <td>10.33</td>\n",
       "      <td>9.38</td>\n",
       "      <td>2009-11-26</td>\n",
       "      <td>000859</td>\n",
       "      <td>10.33</td>\n",
       "      <td>255.0</td>\n",
       "      <td>387</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>2739</td>\n",
       "      <td>5.52</td>\n",
       "      <td>5.75</td>\n",
       "      <td>5.50</td>\n",
       "      <td>2010-06-30</td>\n",
       "      <td>000859</td>\n",
       "      <td>5.50</td>\n",
       "      <td>142.0</td>\n",
       "      <td>216</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>2951</td>\n",
       "      <td>10.29</td>\n",
       "      <td>10.70</td>\n",
       "      <td>9.75</td>\n",
       "      <td>2011-05-20</td>\n",
       "      <td>000859</td>\n",
       "      <td>10.70</td>\n",
       "      <td>212.0</td>\n",
       "      <td>324</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>3450</td>\n",
       "      <td>3.42</td>\n",
       "      <td>3.54</td>\n",
       "      <td>3.25</td>\n",
       "      <td>2013-06-25</td>\n",
       "      <td>000859</td>\n",
       "      <td>3.25</td>\n",
       "      <td>499.0</td>\n",
       "      <td>767</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>3929</td>\n",
       "      <td>14.14</td>\n",
       "      <td>14.68</td>\n",
       "      <td>13.70</td>\n",
       "      <td>2015-06-12</td>\n",
       "      <td>000859</td>\n",
       "      <td>14.68</td>\n",
       "      <td>479.0</td>\n",
       "      <td>717</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>14</th>\n",
       "      <td>4099</td>\n",
       "      <td>4.24</td>\n",
       "      <td>4.55</td>\n",
       "      <td>4.11</td>\n",
       "      <td>2016-02-29</td>\n",
       "      <td>000859</td>\n",
       "      <td>4.11</td>\n",
       "      <td>170.0</td>\n",
       "      <td>262</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>15</th>\n",
       "      <td>4342</td>\n",
       "      <td>7.37</td>\n",
       "      <td>7.67</td>\n",
       "      <td>7.03</td>\n",
       "      <td>2017-03-10</td>\n",
       "      <td>000859</td>\n",
       "      <td>7.67</td>\n",
       "      <td>243.0</td>\n",
       "      <td>375</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>16</th>\n",
       "      <td>4735</td>\n",
       "      <td>2.66</td>\n",
       "      <td>2.68</td>\n",
       "      <td>2.54</td>\n",
       "      <td>2018-10-19</td>\n",
       "      <td>000859</td>\n",
       "      <td>2.54</td>\n",
       "      <td>393.0</td>\n",
       "      <td>588</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>17</th>\n",
       "      <td>4827</td>\n",
       "      <td>9.00</td>\n",
       "      <td>9.99</td>\n",
       "      <td>8.67</td>\n",
       "      <td>2019-03-07</td>\n",
       "      <td>000859</td>\n",
       "      <td>9.99</td>\n",
       "      <td>92.0</td>\n",
       "      <td>139</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>18</th>\n",
       "      <td>4993</td>\n",
       "      <td>3.95</td>\n",
       "      <td>4.10</td>\n",
       "      <td>3.88</td>\n",
       "      <td>2019-11-11</td>\n",
       "      <td>000859</td>\n",
       "      <td>3.88</td>\n",
       "      <td>166.0</td>\n",
       "      <td>249</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>19</th>\n",
       "      <td>5021</td>\n",
       "      <td>6.79</td>\n",
       "      <td>6.96</td>\n",
       "      <td>6.23</td>\n",
       "      <td>2019-12-19</td>\n",
       "      <td>000859</td>\n",
       "      <td>6.96</td>\n",
       "      <td>28.0</td>\n",
       "      <td>38</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>20</th>\n",
       "      <td>5047</td>\n",
       "      <td>4.47</td>\n",
       "      <td>4.52</td>\n",
       "      <td>4.20</td>\n",
       "      <td>2020-02-04</td>\n",
       "      <td>000859</td>\n",
       "      <td>4.20</td>\n",
       "      <td>26.0</td>\n",
       "      <td>47</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>21</th>\n",
       "      <td>5063</td>\n",
       "      <td>6.19</td>\n",
       "      <td>6.91</td>\n",
       "      <td>6.03</td>\n",
       "      <td>2020-02-26</td>\n",
       "      <td>000859</td>\n",
       "      <td>6.91</td>\n",
       "      <td>16.0</td>\n",
       "      <td>22</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>22</th>\n",
       "      <td>5086</td>\n",
       "      <td>4.62</td>\n",
       "      <td>4.78</td>\n",
       "      <td>4.50</td>\n",
       "      <td>2020-03-30</td>\n",
       "      <td>000859</td>\n",
       "      <td>4.50</td>\n",
       "      <td>23.0</td>\n",
       "      <td>33</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>23</th>\n",
       "      <td>5156</td>\n",
       "      <td>6.39</td>\n",
       "      <td>6.65</td>\n",
       "      <td>6.26</td>\n",
       "      <td>2020-07-14</td>\n",
       "      <td>000859</td>\n",
       "      <td>6.65</td>\n",
       "      <td>70.0</td>\n",
       "      <td>106</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>24</th>\n",
       "      <td>5298</td>\n",
       "      <td>4.74</td>\n",
       "      <td>4.84</td>\n",
       "      <td>4.71</td>\n",
       "      <td>2021-02-08</td>\n",
       "      <td>000859</td>\n",
       "      <td>4.71</td>\n",
       "      <td>142.0</td>\n",
       "      <td>209</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>25</th>\n",
       "      <td>5303</td>\n",
       "      <td>5.15</td>\n",
       "      <td>5.33</td>\n",
       "      <td>5.14</td>\n",
       "      <td>2021-02-22</td>\n",
       "      <td>000859</td>\n",
       "      <td>5.33</td>\n",
       "      <td>5.0</td>\n",
       "      <td>14</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>26</th>\n",
       "      <td>5315</td>\n",
       "      <td>4.87</td>\n",
       "      <td>5.00</td>\n",
       "      <td>4.85</td>\n",
       "      <td>2021-03-10</td>\n",
       "      <td>000859</td>\n",
       "      <td>4.85</td>\n",
       "      <td>12.0</td>\n",
       "      <td>16</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>27</th>\n",
       "      <td>5323</td>\n",
       "      <td>5.20</td>\n",
       "      <td>5.24</td>\n",
       "      <td>5.09</td>\n",
       "      <td>2021-03-22</td>\n",
       "      <td>000859</td>\n",
       "      <td>5.24</td>\n",
       "      <td>8.0</td>\n",
       "      <td>12</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>28</th>\n",
       "      <td>5329</td>\n",
       "      <td>4.97</td>\n",
       "      <td>5.03</td>\n",
       "      <td>4.93</td>\n",
       "      <td>2021-03-30</td>\n",
       "      <td>000859</td>\n",
       "      <td>4.93</td>\n",
       "      <td>6.0</td>\n",
       "      <td>8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>29</th>\n",
       "      <td>5335</td>\n",
       "      <td>5.00</td>\n",
       "      <td>5.10</td>\n",
       "      <td>4.99</td>\n",
       "      <td>2021-04-08</td>\n",
       "      <td>000859</td>\n",
       "      <td>5.10</td>\n",
       "      <td>6.0</td>\n",
       "      <td>9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>30</th>\n",
       "      <td>5336</td>\n",
       "      <td>4.98</td>\n",
       "      <td>5.00</td>\n",
       "      <td>4.94</td>\n",
       "      <td>2021-04-09</td>\n",
       "      <td>000859</td>\n",
       "      <td>4.94</td>\n",
       "      <td>1.0</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    index  close   high    low  trade_date ts_code     cv  period  days\n",
       "0       0  12.08  12.50  11.03  1998-11-19  000859  12.50     0.0     0\n",
       "1     318  15.64  15.99  14.50  2000-03-29  000859  15.99   318.0   496\n",
       "2     346  10.23  10.61  10.15  2000-05-15  000859  10.15    28.0    47\n",
       "3     605  13.34  13.52  13.28  2001-06-13  000859  13.52   259.0   394\n",
       "4     755   7.66   7.66   6.54  2002-01-23  000859   6.54   150.0   224\n",
       "5    1042   9.67  10.38   9.45  2003-04-16  000859  10.38   287.0   448\n",
       "6    1702   1.81   1.83   1.78  2006-03-08  000859   1.78   660.0  1057\n",
       "7    1992  11.74  12.00  10.90  2007-05-28  000859  12.00   290.0   446\n",
       "8    2342   2.20   2.30   2.15  2008-11-04  000859   2.15   350.0   526\n",
       "9    2597   9.50  10.33   9.38  2009-11-26  000859  10.33   255.0   387\n",
       "10   2739   5.52   5.75   5.50  2010-06-30  000859   5.50   142.0   216\n",
       "11   2951  10.29  10.70   9.75  2011-05-20  000859  10.70   212.0   324\n",
       "12   3450   3.42   3.54   3.25  2013-06-25  000859   3.25   499.0   767\n",
       "13   3929  14.14  14.68  13.70  2015-06-12  000859  14.68   479.0   717\n",
       "14   4099   4.24   4.55   4.11  2016-02-29  000859   4.11   170.0   262\n",
       "15   4342   7.37   7.67   7.03  2017-03-10  000859   7.67   243.0   375\n",
       "16   4735   2.66   2.68   2.54  2018-10-19  000859   2.54   393.0   588\n",
       "17   4827   9.00   9.99   8.67  2019-03-07  000859   9.99    92.0   139\n",
       "18   4993   3.95   4.10   3.88  2019-11-11  000859   3.88   166.0   249\n",
       "19   5021   6.79   6.96   6.23  2019-12-19  000859   6.96    28.0    38\n",
       "20   5047   4.47   4.52   4.20  2020-02-04  000859   4.20    26.0    47\n",
       "21   5063   6.19   6.91   6.03  2020-02-26  000859   6.91    16.0    22\n",
       "22   5086   4.62   4.78   4.50  2020-03-30  000859   4.50    23.0    33\n",
       "23   5156   6.39   6.65   6.26  2020-07-14  000859   6.65    70.0   106\n",
       "24   5298   4.74   4.84   4.71  2021-02-08  000859   4.71   142.0   209\n",
       "25   5303   5.15   5.33   5.14  2021-02-22  000859   5.33     5.0    14\n",
       "26   5315   4.87   5.00   4.85  2021-03-10  000859   4.85    12.0    16\n",
       "27   5323   5.20   5.24   5.09  2021-03-22  000859   5.24     8.0    12\n",
       "28   5329   4.97   5.03   4.93  2021-03-30  000859   4.93     6.0     8\n",
       "29   5335   5.00   5.10   4.99  2021-04-08  000859   5.10     6.0     9\n",
       "30   5336   4.98   5.00   4.94  2021-04-09  000859   4.94     1.0     1"
      ]
     },
     "execution_count": 235,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "hldata"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "qawork",
   "language": "python",
   "name": "qawork"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
